<template>
  <div>
    <el-row style="margin-top: 0px; background: #f0f2f5">
      <el-col :span="6">
        <!--顶部-->
        <el-row class="topLeft">
          <el-col
            :span="24"
            style="
              line-height: 50px;
              background-color: #0b74fa;
              padding-left: 15px;
              color: white;
            "
          >
            {{ dataInfo.fileType }}-{{ dataInfo.fileName }}
          </el-col>
          <el-col :span="24" class="fieldTitle"> 表单字段 </el-col>
        </el-row>
        <div class="tip_font">点击字段选择插入字段或复制字段代码操作</div>

        <el-row class="left_bottom">
          <el-col v-for="(item, index) in classifyData" :key="index" :span="24">
            <el-col :span="24">
              <div class="classifyTitle">{{ item[0].group || '' }}</div>
            </el-col>

            <el-col :span="24">
              <div class="element">
                <!-- <div
                  v-for="(item1, index1) in item"
                  :key="index1"
                  class="elementTag"
                  :span="8"
                  style="background: #fafafa;"
                >
                  {{ item1.label || '' }}
                </div> -->

                <div class="platform-bar element">
                  <button
                    v-for="(item1, index1) in item"
                    :key="index1"
                    class="elementTag"
                    :span="8"
                    style="background: #fafafa"
                    draggable="true"
                    @dragstart="onDragStart($event, item1)"
                  >
                    {{ item1.label || '' }}
                  </button>
                </div>

                <!-- <el-tag
                  v-for="(item1, index1) in item"
                  :key="item1.label"
                  effect="plain"
                >
                  {{ item1.label }}
                </el-tag> -->
              </div>
            </el-col>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="18">
        <div class="rightBox">
          <el-row class="topRight">
            <el-col
              :span="24"
              style="
                line-height: 50px;
                background-color: #0b74fa;
                padding-left: 15px;
                color: white;
              "
            >
              <div class="topRightNav">
                <el-select
                  v-model="chooseModelName"
                  placeholder="请选择模板"
                  @change="changeModel"
                >
                  <el-option
                    v-for="(item, index) in modelArr"
                    :key="item.id"
                    :label="item.templateName"
                    :value="item.id"
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: space-between;
                    "
                  >
                    <span style="width: 100%" @click="clickOption(item)">{{
                      item.templateName
                    }}</span>
                    <span v-if="item.state == 1" style="float: right; color: #8492a6; font-size: 12px">默认</span>
                    <span v-if="item.defaultTemplateStatus == 1 && item.state != 1" style="float: right; color: #8492a6; font-size: 12px">系统</span>

                    <!-- <i
                      v-if="index > 0"
                      class="el-icon-edit"
                    /> -->
                  </el-option>

                  <el-option
                    style="text-align: center; background: #4889f4; color: #fff"
                    value=""
                  >
                    <span style="width: 100%" @click="addModel">
                      <i class="el-icon-plus" />
                      新增模板
                    </span>
                  </el-option>
                </el-select>

                <div class="topRightBtn">
                  <el-button
                    :loading="loadings"
                    @click="setModel"
                  >设置为默认模板</el-button>
                  <el-button
                    :loading="delLoading"
                    @click="delModel"
                  >删除模板</el-button>
                  <el-button
                    :loading="loading"
                    @click="saveModel"
                  >保存为新模板</el-button>
                  <el-button
                    :loading="loading"
                    @click="saveEdit"
                  >保存编辑</el-button>
                </div>
              </div>
            </el-col>

            <el-dialog
              title="保存模板"
              :visible.sync="commitDialogVisible"
              width="25%"
              center
            >
              <el-form :model="commitForm">
                <el-form-item label="模板名称：">
                  <el-input v-model="commitForm.templateName" />
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="commitForm.defaultTemplateStatus">设置为默认表单</el-checkbox>
                </el-form-item>
              </el-form>
              <span slot="footer" class="dialog-footer">
                <el-button @click="commitDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="commitDialog">确 定</el-button>
              </span>
            </el-dialog>

            <el-col :span="24" class="fieldTitle" style="display: none">
              表单字段
            </el-col>
          </el-row>
          <div class="tip_font" style="display: none">
            点击字段选择插入字段或复制字段代码操作
          </div>
          <div class="textarea">
            <div id="platform" class="platform">
              <div class="platform-editor">
                <textarea id="editor" style="" />
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
const getDataValueByFields = (data, fields) => {
  fields = Array.isArray(fields) ? fields : fields.split('.')
  regexp = /\[(y|x)?\]/gi

  for (let i = 0, l = fields.length; i < l; i++) {
    let field = fields[i]

    if (regexp.test(field)) {
      field = field.replace('[]', '')

      const collection = data[field]
      const values = []

      if (collection && Array.isArray(collection)) {
        for (let m = 0, n = collection.length; m < n; m++) {
          values.push('data-' + m + '="' + getDataValueByFields(collection[m], [].concat(fields).splice(i + 1)) + '"')
        }
      }

      const key = fields.join('.')

      return '<array data-size="' + values.length + '" data-key="' + key.substr(0, key.indexOf('[]')) + '" ' + values.join(' ') + '></array>'
    } else if (data) {
      data = data[field]
    }
  }

  return data
}

const getLoopAncestor = (node, tags) => {
  tags = (tags || '').trim().split(',')
  if (!tags.length) {
    return node.parentNode
  } else {
    let n = node.parentNode
    do {
      if (~tags.indexOf(n.tagName.toLowerCase())) {
        return n
      }
    }
    while (n = n.parentNode)
  }

  return node.parentNode
}

import * as formConfigurationsServer from '@/api/system/formConfigurations'
export default {
  name: 'FormConfigurationComponent',
  data() {
    return {
      isBg: false,
      commitDialogVisible: false,
      showEdit: false,
      loading: false,
      loadings: false,
      delLoading: false,
      dataInfo: '',
      editId: '',
      classifyData: null,
      preview: null,
      htmlJson: '',
      modelArr: [],
      chooseModelName: '',
      opt: 'addModel',
      modelName: '',
      commitForm: {
        templateName: '',
        defaultTemplateStatus: 0
      },
      chooseModelItem: ''
    }
  },
  // created(){
  //     this.querySidebar();
  // },
  mounted() {
    // tinymce.remove('#editor')
    this.dataInfo = this.$route.params.rowInfo
    this.showEdit = true
    this.querySidebar()
    this.refresh()
  },
  destroyed() {
    tinymce.remove('#editor')
  },
  methods: {
    // 初始化表单
    init() {
      tinymce.init({
        selector: '#editor',
        language: 'zh_CN',
        plugins: [
          'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
          'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime',
          'media', 'table', 'emoticons', 'template', 'help'
        ],
        toolbar: ' undo redo | table  | bold italic | alignleft aligncenter alignright alignjustify | ' +
						'bullist numlist outdent indent | link image | print preview media fullscreen | ' +
						'forecolor backcolor emoticons | help',
        contextmenu: 'paste | link image inserttable | cell row column deletetable',
        menu: {
          favs: {
            title: 'My Favorites',
            items: 'code visualaid | searchreplace | emoticons'
          }
        },
        menubar: 'favs file edit view insert format tools table help',
        init_instance_callback: editor => {
          editor.on('change', event => {
            setTimeout(() => {
              const template = document.createElement('div')

              template.innerHTML = editor.getContent().replace(/\${(\S+?)}/gi, ($0, $1) => getDataValueByFields(this.json, $1))
              this.htmlJson = template.innerHTML
              console.log(template.innerHTML, 1111199)
              template.querySelectorAll('array').forEach(node => {
                const loop = getLoopAncestor(node, 'tr,li')
                const container = loop.parentNode
                if (!loop.key) {
                  loop.key = node.dataset.key

                  for (let i = 0, l = parseInt(node.dataset.size); i < l; i++) {
                    const clone = loop.cloneNode(true)

                    clone.querySelectorAll('array').forEach(n => {
                      n.parentNode.innerHTML = n.dataset[i]
                    })

                    container.insertBefore(clone, loop)
                  }

                  container.removeChild(loop)
                }
              })

              this.preview = template.innerHTML
            })
          })

          editor.on('drop', event => {
            editor.insertContent(event.dataTransfer.getData('BIND_DATA'))
          })
        }
      })
    },
    refresh() {
      this.findModel()
      this.init()
    },
    // select change事件
    changeModel(e) {
      this.modelArr.map((item) => {
        if (item.id == e) {
          this.chooseModelItem = item
        }
      })
    },

    // 选中模板
    clickOption(item) {
      // console.log(item.tableData, 3233)
      this.editId = item.id
      this.modelName = item.templateName
      tinyMCE.activeEditor.setContent(item.tableData)
      this.opt = 'addModel'
      this.$forceUpdate()
    },

    // 设置为默认模板
    setModel() {
      this.loadings = true
      if (!this.chooseModelItem) {
        this.$message({
          type: 'warning',
          message: '请选择模板!'
        })

        setTimeout(() => {
          this.loadings = false
        }, 200)
        return
      }

      this.$confirm("是否将<span style='color:red'>" + this.chooseModelItem.templateName + '</span> 设置为默认模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        const params = {
          id: this.chooseModelItem.id, // 模板id
          resourceId: this.dataInfo.id // 表单配置id
        }
        formConfigurationsServer.installDefaultTemplateApi(params).then(res => {
          this.$message({
            type: 'success',
            message: '设置成功!'
          })
        })
        this.refresh()
        this.loadings = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消设置'
        })
        this.loadings = false
      }).finally(() => {
        this.$nextTick(() => {
          this.refresh()
          this.$forceUpdate()
        })
      })
    },
    // 删除模板
    delModel() {
      this.delLoading = true
      if (!this.chooseModelItem) {
        this.$message({
          type: 'warning',
          message: '请选择模板!'
        })
        setTimeout(() => {
          this.delLoading = false
        }, 200)
        return
      }

      this.$confirm("此操作将永久删除该模板<span style='color:red'>" + this.chooseModelItem.templateName + '</span>, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        formConfigurationsServer.deleteTemplateApi({ id: this.chooseModelItem.id }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        this.$nextTick(() => {
          this.refresh()
          this.$forceUpdate()
        })
        this.delLoading = false
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
        this.delLoading = false
      })
    },
    // 编辑模板
    edit(item) {
      this.opt = 'edit'
      this.editId = item.id
      this.modelName = item.templateName
      tinyMCE.activeEditor.setContent(item.tableData)
      this.$forceUpdate()
    },
    // 新增模板
    addModel() {
      this.opt = 'addModel'
      this.modelName = ''
      this.$nextTick(() => {
        tinyMCE.activeEditor.setContent('')
        this.$forceUpdate()
      })
    },
    // 保存弹框提交
    commitDialog() {
      console.log(this.commitForm.templateName, 6666)
      // if (this.commitForm.defaultTemplateStatus) {
      //   this.commitForm.defaultTemplateStatus = 1
      // } else {
      //   this.commitForm.defaultTemplateStatus = 0
      // }
      if (this.opt == 'addModel') {
        const params = {
          templateName: this.commitForm.templateName, // 模板名称
          resourceId: this.dataInfo.id, // 表单配置id
          tableData: this.htmlJson, // table数据
          defaultTemplateStatus: '0' // 是否系统模板
        }
        formConfigurationsServer.addTemplateApi(params).then(res => {
          if (res.code == 200) {
            this.$message({
              type: 'success',
              message: res.message
            })
          } else {
            this.$message({
              type: 'error',
              message: res.message
            })
          }

          this.$nextTick(() => {
            this.refresh()
            this.$forceUpdate()
          })
        })
      } else {
        const params = {
          templateName: this.commitForm.templateName, // 模板名称
          resourceId: this.dataInfo.id, // 表单配置id
          tableData: this.htmlJson, // table数据
          id: this.editId // 编辑的模板表单id
        }
        formConfigurationsServer.uploadTemplateApi(params).then(res => {
          if (res.code != 200) {
            this.$message({
              type: 'error',
              message: res.message
            })
          }

          this.$nextTick(() => {
            this.refresh()
            this.$forceUpdate()
          })
        })
      }
      this.$nextTick(() => {
        if (this.commitForm.defaultTemplateStatus) {
          const params = {
            id: this.chooseModelItem.id, // 模板id
            resourceId: this.dataInfo.id // 表单配置id
          }
          formConfigurationsServer.installDefaultTemplateApi(params).then(ref => {
            this.$message({
              type: 'success',
              message: '设置成功!'
            })
          })
        }
        this.loading = false
        this.commitDialogVisible = false
      })
    },
    // 保存模板
    saveModel() {
      this.opt = 'addModel'
      this.commitDialogVisible = true
      this.commitForm.templateName = this.modelName
      // this.$prompt('模板名称', '', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputPattern: /\S/,
      //   inputValue: this.modelName,
      //   inputErrorMessage: '请输入模板名称'
      // }).then(({ value }) => {
      //   const params = {
      //     templateName: value, // 模板名称
      //     resourceId: this.dataInfo.id, // 表单配置id
      //     tableData: this.htmlJson, // table数据
      //     defaultTemplateStatus: 0 // 是否系统模板
      //   }
      //   formConfigurationsServer.addTemplateApi(params).then(res => {
      //     if (res.code == 200) {
      //       this.$message({
      //         type: 'success',
      //         message: res.message
      //       })
      //     }

      //     this.$nextTick(() => {
      //       this.refresh()
      //       this.$forceUpdate()
      //     })
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   })
      // }).finally(() => {
      //   this.loading = false
      // })
    },

    // 保存编辑模板
    saveEdit() {
      if (!this.chooseModelItem) {
        this.$message({
          type: 'warning',
          message: '请选择模板!'
        })
        setTimeout(() => {
          this.loading = false
        }, 200)
        return
      }
      this.commitForm.templateName = this.modelName
      this.opt = 'edit'
      this.commitDialogVisible = true

      // this.$prompt('模板名称', '', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   inputPattern: /\S/,
      //   inputValue: this.modelName,
      //   inputErrorMessage: '请输入模板名称'
      // }).then(({ value }) => {
      //   const params = {
      //     templateName: value, // 模板名称
      //     resourceId: this.dataInfo.id, // 表单配置id
      //     tableData: this.htmlJson, // table数据
      //     id: this.editId // 编辑的模板表单id
      //   }
      //   formConfigurationsServer.uploadTemplateApi(params).then(res => {
      //     if (res.code == 200) {
      //       this.$message({
      //         type: 'success',
      //         message: res.message
      //       })
      //     }

      //     this.$nextTick(() => {
      //       this.refresh()
      //       this.$forceUpdate()
      //     })
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   })
      // }).finally(() => {
      //   this.loading = false
      // })
    },

    // 查询自定义模板
    findModel() {
      formConfigurationsServer.queryTemplateByConditionApi({ resourceId: this.dataInfo.id }).then(res => {
        console.log(res.result, 456)
        this.modelArr = res.result
        if (Array.isArray(res.result)) {
          const nationalities = res.result
          nationalities.map((item) => {
            if (item.state == '1') {
              tinyMCE.activeEditor.setContent(item.tableData)
            }
          })

          // const delNationIndex = nationalities.findIndex((item) => {
          //   return item.state == '1'
          // })
        //   console.log(delNationIndex, 'delNationIndex')
        //   const nation = nationalities[delNationIndex ]
        //   // 2 在数组中删除1
        //   nationalities.splice(delNationIndex, 1)
        //   // 3 在最头上添加相应的元素
        //   nationalities.unshift(nation)
        //   this.clickOption(nation)
        //   this.chooseModelName = nation.templateName
        //   this.modelArr = nationalities
        }

        this.$forceUpdate()
      })
    },
    onDragStart(event, data) {
      console.log(data, 999)
      var key = ''
      if (data.group == '水质现场因子') {
        key = '{' + this.getCaption(data.label, 0) + '}'
      } else {
        key = '{' + data.value + '}'
      }

      event.dataTransfer.setData('BIND_DATA', key)
    },
    // 截取（ 前的内容
    getCaption(obj, state) {
      var index = obj.lastIndexOf('\（')
      if (index < 0) {
        index = obj.lastIndexOf('\(')
      }
      if (state == 0) {
        obj = obj.substring(0, index)
      } else {
        obj = obj.substring(index + 1, obj.length)
      }
      return obj
    },
    test() {
      this.isBg = true
    },

    // 查询右侧字段分类
    querySidebar() {
      formConfigurationsServer.queryCategoryByConditionApi({ fileResourceId: this.dataInfo.id }).then(res => {
        this.classifyData = this.sortArr(res.result[0].fieldName, 'group')

        console.log({ ...this.classifyData }, 6666)
        this.$forceUpdate()
      })
    },
    // 处理数据
    sortArr(arr, str) {
      var _arr = []
      var _t = []
      // 临时的变量
      var _tmp

      // 按照特定的参数将数组排序将具有相同值得排在一起
      arr = arr.sort(function(a, b) {
        var s = a[str]
        var t = b[str]

        return s < t ? -1 : 1
      })

      if (arr.length) {
        _tmp = arr[0][str]
      }
      // console.log( arr );
      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === _tmp) {
          _t.push(arr[i])
        } else {
          _tmp = arr[i][str]
          _arr.push(_t)
          _t = [arr[i]]
        }
      }
      // 将最后的内容推出新数组
      _arr.push(_t)
      return _arr
    }
  }
}
</script>

<style scoped>
.platform {
  display: flex;
}

.platform-bar {
  width: 100%;
  flex-grow: 0;
  flex-shrink: 0;
}

.platform-editor {
  width: 100%;
  height: 100%;
  flex-grow: 0;
  flex-shrink: 0;
}

.platform-preview {
  flex-grow: 1;
  flex-shrink: 1;
}

.platform-preview textarea {
  display: block;
  width: 100%;
  resize: vertical;
}
.bg-color {
  background-color: #409eff !important;
  color: white;
}
.topLeft {
  box-shadow: 1px 0 3px #ccc;
}
.fieldTitle {
  height: 50px;
  line-height: 50px;
  text-align: center;
  background-color: #fff;
  font-weight: bolder;
}
.tip_font {
  text-align: center;
  color: #878d99;
  padding: 10px;
  font-size: 14px;
}
.rightBox {
  width: 100%;
  height: 100%;
  background: transparent;
  padding-left: 10px;
}
.topRightNav {
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
.left_bottom {
  height: calc(100vh - 210px);
  overflow: auto;
  margin-bottom: 10px;
  padding: 0 8px;
  padding-bottom: 30px;
  box-shadow: 1px 1px 3px #ccc;
}
.element {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
}
.elementTag {
  width: 48%;
  padding: 10px 5px;
  margin-top: 8px;
  text-align: center;
  font-size: 14px;
  font-weight: 700;
  border-radius: 4px;
  box-shadow: 0 0 3px #ccc;
  background-color: white;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  border: 0;
}
.classifyTitle {
  font-size: 14px;
  font-weight: bolder;
  color: #4889f4;
  line-height: 40px;
  border-bottom: 1px solid #4889f4;
}
.textarea {
  width: 100%;
  height: calc(100vh - 205px);
}
/deep/.tox-tinymce {
  height: calc(100vh - 205px) !important;
}
/deep/.tox-statusbar__branding {
  display: none;
}
</style>
